package com.wash.shoes.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.wash.shoes.common.enums.FactoryStatusEnum;
import com.wash.shoes.common.enums.UserBindTypeEnum;
import com.wash.shoes.entity.ShopPo;
import com.wash.shoes.entity.UserShopPo;
import com.wash.shoes.mapper.FactoryMapper;
import com.wash.shoes.mapper.UserShopMapper;
import com.wash.shoes.page.PageFactory;
import com.wash.shoes.request.BindUserShopRequest;
import com.wash.shoes.request.GetUnbindDataRequest;
import com.wash.shoes.resp.BindRecordResp;
import com.wash.shoes.service.UserShopService;

import cn.hutool.core.lang.Assert;

/**
 * <p>
 * 用户关联的店铺 服务实现类
 * </p>
 *
 * @author ljg
 * @since 2024-10-11
 */
@Service
public class UserShopServiceImpl extends ServiceImpl<UserShopMapper, UserShopPo> implements UserShopService {
    @Autowired
    private FactoryMapper factoryMapper;
    @Autowired
    private UserShopMapper userShopMapper;

    /**
     * 获取未绑定/已绑定的列表
     *
     * @param getUnbindDataRequest 请求参数
     * @return
     */
    @Override
    public /*List<BindRecordResp>*/IPage<BindRecordResp> getUnBindList(GetUnbindDataRequest getUnbindDataRequest) {
        IPage<BindRecordResp> page = null;
        List<BindRecordResp> data = new ArrayList<>();
        if (UserBindTypeEnum.FACTORY == getUnbindDataRequest.getBindType()) {
            /*data*/ page = factoryMapper.getUnBindList(getUnbindDataRequest.toPage(), getUnbindDataRequest.getAction(),
                getUnbindDataRequest.getUserId(), UserBindTypeEnum.FACTORY.getCode(),
                FactoryStatusEnum.NORMAL.getCode(), getUnbindDataRequest.getName());
        } else {
            /*data*/page = userShopMapper.getUnBindList(getUnbindDataRequest.toPage(), getUnbindDataRequest.getAction(),
                getUnbindDataRequest.getUserId(), UserBindTypeEnum.SHOP.getCode(), "1", getUnbindDataRequest.getName(),
                getUnbindDataRequest.getBrandId(), getUnbindDataRequest.getChannel());
        }
        // page.toPageInfo()
        return page;
    }

    @Override
    public Page<ShopPo> noConnectionShopList(String shopName, String userId, String type) {
        Page page = PageFactory.defaultPage();
        List<ShopPo> dataList = this.baseMapper.noConnectionShopList(page, shopName, userId, type);
        page.setRecords(dataList);
        return page;
    }

    @Override
    public Page<ShopPo> userShopList(String userId) {
        Page page = PageFactory.defaultPage();
        List<ShopPo> dataList = this.baseMapper.userShopList(page, userId);
        page.setRecords(dataList);
        return page;
    }

    @Override
    public List<ShopPo> userAllShopList(String userId) {
        return this.baseMapper.userAllShopList(userId);
    }

    @Override
    public UserShopPo userAssociateShopData(String userId, String shopId) {
        return this.baseMapper.userAssociateShopData(userId, shopId);
    }

    @Override
    public UserShopMapper getBaseMapper() {
        return super.getBaseMapper();
    }

    /**
     * 批量绑定用户和门店关系
     *
     * @param bindUserShopRequest 绑定请求对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchBindUserShop(@RequestBody @Valid BindUserShopRequest bindUserShopRequest) {
        /*        this.baseMapper
            .delete(new LambdaQueryWrapper<UserShopPo>().eq(UserShopPo::getUserId, bindUserShopRequest.getUserId()));*/
        List<UserShopPo> data = this.baseMapper.selectList(new LambdaQueryWrapper<UserShopPo>()
            .eq(UserShopPo::getStatus, 1).eq(UserShopPo::getUserId, bindUserShopRequest.getUserId()));

        Set<UserBindTypeEnum> bindType = data.stream().map(UserShopPo::getType).collect(Collectors.toSet());
        if (Objects.isNull(bindType)) {
            bindType = new HashSet<>();
        }
        bindType.add(bindUserShopRequest.getType());

        Assert.isTrue(bindType.size() == 1, "用户已绑定了类型，请勿重复绑定");
        LoginUser loginUser = getLoginUser();
        List<UserShopPo> userShopPoList = bindUserShopRequest.getBizId().stream().map(bizId -> {
            UserShopPo userShopPo = new UserShopPo();
            userShopPo.setUserId(bindUserShopRequest.getUserId());
            userShopPo.setShopId(bizId);
            userShopPo.setStatus(1);
            userShopPo.setCreateTime(new Date());
            userShopPo.setUpdateTime(new Date());
            userShopPo.setCreateBy(Objects.nonNull(loginUser) ? loginUser.getUsername() : "system");
            userShopPo.setUpdateBy(Objects.nonNull(loginUser) ? loginUser.getUsername() : "system");
            userShopPo.setType(bindUserShopRequest.getType());
            return userShopPo;
        }).collect(Collectors.toList());

        /*  return this.saveOrUpdateBatch(userShopPoList);*/
        return saveBatch(userShopPoList);
    }

    private LoginUser getLoginUser() {
        try {
            return SecurityUtils.getLoginUser();
        } catch (Exception e) {
            return null;
        }
    }
}